//
//  TodoItem.swift
//  Todo-List
//
//  Created by stu on 2019/9/23.
//  Copyright © 2019年 stu. All rights reserved.
//

import Foundation
import UserNotifications

class TodoItem:NSObject,NSCoding {
    func encode(with aCoder: NSCoder) {
        aCoder.encode(text, forKey: "Text")
        aCoder.encode(checked, forKey: "Checked")
    }
    
    required init?(coder aDecoder: NSCoder) {
       text = aDecoder.decodeBool(forKey: "Text") as! String
       checked = aDecoder.decodeBool(forKey: "Checked")
        dueDate = aDecoder.decodeObject(forKey:"DueDate") as! Date
        shouldRemind = aDecoder.decodeBool(forKey: "ShouldRemind")
        super.init()
    }
    
    var text = ""
    var checked = false
    var dueDate = Date()
    var shouldRemind = false
    
   override init(){
        super.init()
    }
    func scheduleNotification() {
        removeNotification()
        
        if shouldRemind && dueDate > Date() {
            let content = UNMutableNotificationContent()
            content.title = "备忘录"
            content.body = text
            content.sound = UNNotificationSound.default()
            
            let calender = Calendar(identifier: .gregorian)
            let component = calender.dateComponents([.month, .day, .hour, .minute], from: dueDate)
            
            
            let trigger = UNCalendarNotificationTrigger(dateMatching:component,repeats:false)
            let request = UNNotificationRequest(identifier:text, content: content, trigger: trigger)
            let center = UNUserNotificationCenter.current()
            
            center.add(request)
        }
    }
    
    func removeNotification() {
        let center = UNUserNotificationCenter.current()
        center.removePendingNotificationRequests(withIdentifiers: [text])
    }
    
    deinit {
        removeNotification()
    }
}
